package com.emperor.customer.app;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;

import com.emperor.cashier.app.CashierAppCtrl;
import com.emperor.cashier.app.CashierAppForm;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.customer.logic.Customer;
import com.emperor.customer.logic.CustomerModel;
import com.emperor.employee.logic.Employee;
import com.emperor.employee.logic.EmployeeModel;
import com.emperor.util.DateFormatter;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class CustomerAppEnq extends AppBase implements App {

	private Combo monthCombo;
	private Text toText;
	private Text fromText;
	protected Shell shell;
	protected static Logger log = Logger.getLogger(CustomerAppEnq.class);
	private SimpleDateFormat sdf = new SimpleDateFormat(DateFormatter.YYYYMMDD);

	public CustomerAppEnq() {
		super();
	}

	public CustomerAppEnq(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CustomerAppEnq window = new CustomerAppEnq();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shell.setBackgroundImage(SWTResourceManager.getImage(
				CustomerAppEnq.class, "/img/main.jpg"));
		shell.setImage(SWTResourceManager.getImage(CustomerAppEnq.class,
				"/img/iMac OSX.png"));
		shell.setSize(1280, 800);
		shell.setText("Search Customer");

		initScreen(shell, getParams());

		final Composite composite = new Composite(shell, SWT.NONE);
		composite.setBounds(10, 50, 1252, 111);

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		messageLabel.setBounds(10, 10, 852, 25);

		final Table table = new Table(shell, SWT.FULL_SELECTION | SWT.BORDER);
		table.setHeaderVisible(true);
		table.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		table.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent e) {
				editCustomer(table, messageLabel);
			}
		});
		table.setLinesVisible(true);
		table.setBounds(10, 167, 1252, 463);

		final Label customerNameLabel = new Label(composite, SWT.NONE);
		customerNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		customerNameLabel.setText("Customer Name");
		customerNameLabel.setBounds(20, 44, 115, 20);

		final Text text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		text.setToolTipText("cust_name");
		text.setBounds(150, 41, 445, 25);

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setWidth(41);
		newColumnTableColumn.setText("No.");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(271);
		newColumnTableColumn_1.setText("Name");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(104);
		newColumnTableColumn_2.setText("Code");

		final TableColumn newColumnTableColumn_5 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_5.setWidth(124);
		newColumnTableColumn_5.setText("Phone");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_3.setWidth(121);
		newColumnTableColumn_3.setText("Join Date");

		final TableColumn newColumnTableColumn_4 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_4.setWidth(114);
		newColumnTableColumn_4.setText("Expiry Date");

		final TableColumn newColumnTableColumn_6 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_6.setWidth(182);
		newColumnTableColumn_6.setText("Created By");

		final Button addNewCustomerButton = new Button(shell, SWT.NONE);
		addNewCustomerButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		addNewCustomerButton.setImage(SWTResourceManager.getImage(
				CustomerAppEnq.class, "/img/Symbol-Add.png"));
		addNewCustomerButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getParams().put(AppConstant.APPCTRL, CustomerAppCtrl.CUST_CTRL);
				getParams().put(AppConstant.ACTION, CustomerAppCtrl.CUST_NEW);
				getShell().close();
			}
		});
		addNewCustomerButton.setText("Add");
		addNewCustomerButton.setBounds(10, 636, 65, 30);

		final Button deleteCustomerButton = new Button(shell, SWT.NONE);
		deleteCustomerButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		deleteCustomerButton.setImage(SWTResourceManager.getImage(
				CustomerAppEnq.class, "/img/Symbol-Delete.png"));
		deleteCustomerButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
			}
		});
		deleteCustomerButton.setText("Delete");
		deleteCustomerButton.setBounds(177, 636, 85, 30);

		final Button updateCustomerButton = new Button(shell, SWT.NONE);
		updateCustomerButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		updateCustomerButton.setImage(SWTResourceManager.getImage(
				CustomerAppEnq.class, "/img/Edit.png"));
		updateCustomerButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				editCustomer(table, messageLabel);
			}
		});
		updateCustomerButton.setText("Update");
		updateCustomerButton.setBounds(81, 636, 90, 30);

		final Label dateOfBirthLabel = new Label(composite, SWT.NONE);
		dateOfBirthLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		dateOfBirthLabel.setText("Month of Birth");
		dateOfBirthLabel.setBounds(20, 77, 100, 20);

		final Label fromLabel = new Label(composite, SWT.NONE);
		fromLabel.setVisible(false);
		fromLabel.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		fromLabel.setText("From");
		fromLabel.setBounds(610, 42, 40, 20);

		final Label toLabel = new Label(composite, SWT.NONE);
		toLabel.setVisible(false);
		toLabel.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		toLabel.setText("To");
		toLabel.setBounds(877, 42, 20, 20);

		fromText = new Text(composite, SWT.BORDER);
		fromText.setVisible(false);
		fromText.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		fromText.setBounds(656, 39, 152, 25);

		toText = new Text(composite, SWT.BORDER);
		toText.setVisible(false);
		toText.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		toText.setBounds(903, 39, 152, 25);

		final Button button = new Button(composite, SWT.NONE);
		button.setVisible(false);
		button.setImage(SWTResourceManager.getImage(CustomerAppEnq.class,
				"/img/Calendar.png"));
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				pickDate(getShell(), fromText);
			}
		});
		button.setBounds(814, 35, 30, 30);

		final Button button_1 = new Button(composite, SWT.NONE);
		button_1.setVisible(false);
		button_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				pickDate(getShell(), toText);
			}
		});
		button_1.setImage(SWTResourceManager.getImage(CustomerAppEnq.class,
				"/img/Calendar.png"));
		button_1.setBounds(1061, 38, 30, 30);

		final Button searchButton = new Button(composite, SWT.NONE);
		searchButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		searchButton.setImage(SWTResourceManager.getImage(CustomerAppEnq.class,
				"/img/Zoom-in.png"));
		searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				populateTable(table, text.getText(), fromText.getText(), toText
						.getText(), monthCombo.getText(), messageLabel);
			}
		});
		searchButton.setText("Search");
		searchButton.setBounds(416, 72, 90, 30);

		monthCombo = new Combo(composite, SWT.NONE);
		monthCombo.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		monthCombo.setBounds(150, 72, 260, 28);
		monthCombo.add(AppConstant.MONTH_JAN);
		monthCombo.add(AppConstant.MONTH_FEB);
		monthCombo.add(AppConstant.MONTH_MAR);
		monthCombo.add(AppConstant.MONTH_APR);
		monthCombo.add(AppConstant.MONTH_MAY);
		monthCombo.add(AppConstant.MONTH_JUN);
		monthCombo.add(AppConstant.MONTH_JUL);
		monthCombo.add(AppConstant.MONTH_AUG);
		monthCombo.add(AppConstant.MONTH_SEP);
		monthCombo.add(AppConstant.MONTH_OCT);
		monthCombo.add(AppConstant.MONTH_NOV);
		monthCombo.add(AppConstant.MONTH_DEC);

		//
		buildStandardMenu(getShell(), getParams(), CashierAppCtrl.CASHIER_CTRL,
				CashierAppCtrl.CASHIER_FORM);
		populateTable(table, text.getText(), fromText.getText(), toText
				.getText(), monthCombo.getText(), messageLabel);

	}

	public void populateTable(Table table, String name, String from, String to,
			String month, Label label) {
		table.removeAll();
		table.clearAll();
		table.redraw();
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();

			// Criteria cris = session.createCriteria(CustomerModel.class);
			// if (!StringUtils.isEmpty(name)) {
			// cris.add(Expression.like(Customer.FLD_NAME, "%" + name + "%"));
			// }

			// if (!StringUtils.isEmpty(from)) {
			// cris.add(Expression.ge(Customer.FLD_BIRTHDATE, sdf.parse(from)));
			// }
			//			
			// if (!StringUtils.isEmpty(to)) {
			// cris.add(Expression.le(Customer.FLD_BIRTHDATE, sdf.parse(to)));
			// }

			String squery = "SELECT * FROM CUSTOMER WHERE NAME LIKE :name";
			
			Query query = null;
			
			if (!StringUtils.isEmpty(month)) {
				squery += " AND MONTH(BIRTHDATE)=:month";
				int imonth = 1;
				if (AppConstant.MONTH_JAN.equals(month)) {
					imonth = 1;
				} else if (AppConstant.MONTH_FEB.equals(month)) {
					imonth = 2;
				} else if (AppConstant.MONTH_MAR.equals(month)) {
					imonth = 3;
				} else if (AppConstant.MONTH_APR.equals(month)) {
					imonth = 4;
				} else if (AppConstant.MONTH_MAY.equals(month)) {
					imonth = 5;
				} else if (AppConstant.MONTH_JUN.equals(month)) {
					imonth = 6;
				} else if (AppConstant.MONTH_JUL.equals(month)) {
					imonth = 7;
				} else if (AppConstant.MONTH_AUG.equals(month)) {
					imonth = 8;
				} else if (AppConstant.MONTH_SEP.equals(month)) {
					imonth = 9;
				} else if (AppConstant.MONTH_OCT.equals(month)) {
					imonth = 10;
				} else if (AppConstant.MONTH_NOV.equals(month)) {
					imonth = 11;
				} else if (AppConstant.MONTH_DEC.equals(month)) {
					imonth = 12;
				}
				query = session.createSQLQuery(squery).addEntity(
						CustomerModel.class);
				query.setString("name", "%" + name + "%");
				query.setInteger("month", imonth);
			} else {
				query = session.createSQLQuery(squery).addEntity(
						CustomerModel.class);
				query.setString("name", "%" + name + "%");
			}

			List<Customer> customers = query.list();
			if (customers != null) {
				int count = 0;
				for (Iterator<Customer> iter = customers.iterator(); iter
						.hasNext();) {
					Customer customer = iter.next();
					count++;
					Employee employee = (Employee) session.get(
							EmployeeModel.class, customer.getCrtby());
					TableItem item = new TableItem(table, SWT.BORDER);
					item.setText(new String[] { count + ".",
							customer.getName(), customer.getCode(),
							customer.getPhone(),
							sdf.format(customer.getCrtdate()),
							sdf.format(customer.getExpirydate()),
							employee.getName() });
					item.setData(customer);
				}

				if (count > 0) {
					label.setText(count + " customer(s) found.");
				} else {
					label
							.setText("Please enter the customer name and click search.");
				}
			}
		} catch (Exception e) {
			label.setText("no customer found.");
			log.error(e.getMessage(), e);
		}
	}

	private void editCustomer(Table table, Label label) {
		TableItem[] items = table.getSelection();
		if (items != null && items.length > 0) {
			for (int i = 0; i < items.length; i++) {
				TableItem item = items[i];
				if (item.getData() != null) {
					Customer customer = (Customer) item.getData();
					getParams().put(CustomerAppCtrl.CUST_ID, customer.getId());
				}
			}

			getParams().put(AppConstant.APPCTRL, CustomerAppCtrl.CUST_CTRL);
			getParams().put(AppConstant.ACTION, CustomerAppCtrl.CUST_MGM);
			getShell().close();
		} else {
			label.setText("No customer selected");
		}
	}

	public Shell getShell() {
		return shell;
	}

	public void setShell(Shell shell) {
		this.shell = shell;
	}

}
